package leetcodeHis.算法总纲.链表;

public class LinkedList {

    int length = 0;

    //哨兵节点
    ListNode head = new ListNode(-1);

    /**
     * 尾插法
     * @param val
     */
    public void addNode(int val) {
        ListNode temp = head;
        //找到最后一个节点
        while (temp.next != null) {
            temp = temp.next;
        }
        temp.next = new ListNode(val);
        length++;
    }

    /**
     * 头插法
     * @param val
     */
    public void headInsert(int val) {
        ListNode newHead = new ListNode(val);
        newHead.next = head.next;
        head.next = newHead;
        length++;
    }

    public ListNode reverse(ListNode node) {
        ListNode pre = node;
        ListNode cur = node.next;
        pre.next = null;

        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    /**
     * 反转部分链表
     * @param fromIndex
     * @param toIndex
     * @throws Exception
     */
    public ListNode iterationInvertLinkedList(int fromIndex, int toIndex) throws Exception{
        ListNode newList = head.next;

        int index = 1;
        while (fromIndex > index+1) {
            newList = newList.next;
            index++;
        }

        ListNode start = newList.next;   //停在开始位置
        ListNode list = new ListNode(-1);
        ListNode listSee = list;
        while (index+1 <= toIndex) {
            listSee.next = new ListNode(start.val);
            start = start.next;
            listSee = listSee.next;
            index++;
        }
        LinkedList l = new LinkedList();
        l.reverse(list);
        newList.next = list;
        ListNode index1 = list;
        while (list.next != null) {
            index1 = index1.next;
        }
        index1.next = start;

        return head.next;

    }

    public static void main(String[] args) throws Exception {
        LinkedList linkedList = new LinkedList();
        linkedList.addNode(1);
        linkedList.addNode(2);
        linkedList.addNode(3);
        linkedList.addNode(4);

//        ListNode node = linkedList.reverse(linkedList.head.next);
//        while (node!=null) {
//            System.out.print(node.val + "--->");
//            node = node.next;
//        }

        ListNode node1 = linkedList.iterationInvertLinkedList(2,3);
        while (node1 != null) {
            System.out.print(node1.val + "--->");
            node1 = node1.next;
        }
    }


}
